package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;
    @Override
    public Result login(UserLoginDTO dto) {
        //1.获取当前微信号的身份信息：openid
        //1.1 根据AppID +AppSecret + code，去微信平台发请求换取openid
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",dto.getCode());
        map.put("grant_type","authorization_code");
        String jsonStr = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        //1.2 把得到的结果json字符串,转换成java对象，常用的Java工具有：jackson，Fastjson，Gson
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String openid = jsonObject.getString("openid");
        if (openid == null || "".equals("openid")) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //2.把微信账户信息存储倒数据库的user表里
        //2.1现根据openid，从user表里查询一下
        User user = userMapper.selectByOpenId(openid);
        //2.2如果查不到，就需要插入到user表里
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        //3.准备token令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        //4.返回结果
        UserLoginVO vo = new UserLoginVO();
        vo.setId(user.getId());
        vo.setOpenid(openid);
        vo.setToken(token);
        return Result.success(vo);
    }
}
